import java.util.*;

public class Solution {
    public List<String> topKFrequent(String[] words, int k){
        Map<String,Integer> map=new HashMap<>();
        for (String word:words){
            map.put(word,map.getOrDefault(word,0)+1);
        }
          //sort
        List<Map.Entry<String,Integer>>entries=new ArrayList<>(map.entrySet());
        Collections.sort(entries,(a,b)->{
            //sort by freq
            int ret=Integer.compare(b.getValue(),a.getValue());
            if(ret==0){
                //sort by lexicographical
                return a.getKey().compareTo(b.getKey());
            }
            return ret;
        });
        List<String> ret = new ArrayList<>();
        for (Map.Entry<String, Integer> entry:entries) {
            if(ret.size()>=k){
                break;
            }
            ret.add(entry.getKey());
        }
        return ret;
    }
}




